package cc.admin.config;

import cc.admin.common.db.util.TenantUtil;
import cc.admin.common.sys.vo.LoginUser;
import cc.admin.config.mybatis.TenantLineInnerInterceptorReplaceAlign;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.baomidou.mybatisplus.extension.plugins.inner.DynamicTableNameInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.google.common.collect.ImmutableList;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.apache.shiro.SecurityUtils;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.List;

/**
 * 单数据源配置（jeecg.datasource.open = false时生效）
 *
 * @Author zhoujf
 */
@Configuration
@MapperScan(value = {"cc.admin.modules.**.mapper*"})
@Slf4j
public class MybatisPlusConfig {

	List<String> ignoreTableList = ImmutableList.of("sys_log","sys_company","sys_licence","wea_api");

	@Bean
	public MybatisPlusInterceptor mybatisPlusInterceptor() {
		MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
		interceptor.addInnerInterceptor(new TenantLineInnerInterceptorReplaceAlign(new TenantLineHandler() {
			@Override
			public Expression getTenantId() {
				LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
				String tenantId = "anon";
				if (sysUser != null) {
					tenantId = sysUser.getTenantId();
				}
				return new StringValue(tenantId);
			}

			// 这是 default 方法,默认返回 false 表示所有表都需要拼多租户条件
			@Override
			public boolean ignoreTable(String tableName) {
				return ignoreTableList.contains(tableName.toLowerCase());
			}
		}));

		DynamicTableNameInnerInterceptor dynamicTableNameInnerInterceptor = new DynamicTableNameInnerInterceptor();
		dynamicTableNameInnerInterceptor.setTableNameHandler((sql, tableName) -> {
			return TenantUtil.replaceTenantTableName(tableName);
		});
		interceptor.addInnerInterceptor(dynamicTableNameInnerInterceptor);

		interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
		return interceptor;
	}
	//    /**
//     * mybatis-plus SQL执行效率插件【生产环境可以关闭】
//     */
//    @Bean
//    public PerformanceInterceptor performanceInterceptor() {
//        return new PerformanceInterceptor();
//    }

}
